#include <iostream>
#include <fstream>

#include "aktazo.h"
#include "menu.h"

///aktazo.cpp
///class implementation for aktazo.h

Aktazo::Aktazo():filename("adatok.dat"),v_ptr(new std::vector<Document>)
{
	try
	{
		load_data();
		run();
		save_data();
	}
	catch(Exceptions e)
	{
		switch(e)
		{
			case FILE_READ_ERROR:
			{
				std::cerr<<"Hiba: a(z) '"<<filename<<"' fajlt nem lehetett olvasasra megnyitni."<<std::endl;
				break;
			}
			case FILE_WRITE_ERROR:
			{
				std::cerr<<"Hiba: a(z) '"<<filename<<"' fajlt nem lehetett irasra megnyitni."<<std::endl;
				break;
			}
			default:
			{
				std::cerr<<"Hiba: kezeletlen kivetel itt: Aktazo::."<<std::endl;
				break;
			}
		}
	}
}

Aktazo::~Aktazo()
{
	if(f_out.is_open())
	{
		f_out.close();
	}
	if(f_in.is_open())
	{
		f_in.close();
	}
}

void Aktazo::load_data()
{
	std::clog<<"*** LOAD_DATA ***"<<std::endl;
	f_in.open(filename.c_str());
	if(f_in.fail())
	{
		throw FILE_READ_ERROR;
	}
	while(!f_in.eof())
	{
		int e;
		f_in>>e;
		Document d(e);
		v_ptr->push_back(d);
	}
	f_in.close();
	v_old_size=v_ptr->size();
}

void Aktazo::run()
{
	std::cerr<<"*** RUN ***"<<std::endl;
	
	Menu menu(v_ptr);
}

void Aktazo::save_data()
{
	std::cerr<<"*** SAVE_DATA ***"<<std::endl;
	v_new_size=v_ptr->size();
	f_out.open(filename.c_str());
	if(f_out.fail())
	{
		throw FILE_WRITE_ERROR;
	}
	//std::cerr<<v_old_size<<','<<v_new_size<<std::endl;
	for(unsigned int i=0;i<v_new_size;++i)
	{
		std::cerr<<1+i<<':'<<v_ptr->at(i).get_x()<<std::endl;
		if(0!=i)
		{
			f_out<<std::endl;
		}
		f_out<<v_ptr->at(i).get_x();
	}
	f_out.close();
}